package com.zking.filter;

import com.sun.deploy.net.HttpRequest;
import com.zking.dao.HistoryDao;
import com.zking.entity.HistoryItem;
import com.zking.entity.User;
import com.zking.util.Tools;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HistoryFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        HttpSession session = httpRequest.getSession(false);

        if(session == null || session.getAttribute("user")==null){
            chain.doFilter(request, response);
            return;
        }

        User user = (User) session.getAttribute("user");

        int max_count = 2;
        List<HistoryItem> list = HistoryDao.getHistoryItemList(user.getEu_user_id(), max_count);
        List<String> images = new ArrayList<>();
        for(HistoryItem item : list){
            byte[] tmp = item.getEp_image();
            if(tmp!=null){
                images.add(Tools.bytesToString(tmp));
            }else{
                images.add("");
            }
        }
        httpRequest.setAttribute("history_list", list);
        httpRequest.setAttribute("history_images", images);
        chain.doFilter(request, response);
    }
}
